package main

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
	"goods_srv/global"
	"goods_srv/goodsPb"
	"goods_srv/handler"
	_ "goods_srv/initialize"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"net"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	zap.S().Info(global.AppConf)
	//注册微服务 创建一个grpc服务器实例
	g := grpc.NewServer()

	s := handler.GoodsService{}

	goods_pb.RegisterGoodsServer(g, &s)

	//监听指定的网络和端口
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", global.AppConf.Ip, global.AppConf.Port))
	if err != nil {
		zap.S().Panic(err)
	}
	//注册健康状态检查
	grpc_health_v1.RegisterHealthServer(g, health.NewServer())
	//开启一个协程 启动服务器并开始监听
	go func() {
		err := g.Serve(listen)
		if err != nil {
			zap.S().Panic(err)
		}
	}()

	// 注销服务
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", global.AppConf.ConsulConfig.ConsulHost, global.AppConf.ConsulConfig.ConsulPort)
	//实例化consul客户端
	client, err := api.NewClient(config)
	if err != nil {
		zap.S().Panic(err)
	}
	err = client.Agent().ServiceDeregister(global.ServerId)
	if err != nil {
		zap.S().Info("服务注销失败")
		return
	}

	zap.S().Info("服务注销成功")
}
